package com.ccc.oa.user.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ccc.oa.common.core.entity.OaUser;
import com.ccc.oa.common.core.excepiton.CommonExcepiton;
import com.ccc.oa.common.core.utils.JwtUtils;
import com.ccc.oa.user.mapper.UserMapper;
import com.ccc.oa.user.param.LoginParam;
import com.ccc.oa.user.service.UserService;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * --- 代码敲对！ ---
 *
 * @author CCCccc
 * @create 2025/10/10
 * 备注：用户相关功能业务层实现类
 */
// 该注解表示该类为服务层
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 登录功能方法
     */
    @Override
    public String login(LoginParam loginParam) {
        OaUser user = userMapper.selectOne(Wrappers.lambdaQuery(OaUser.class)
                .eq(OaUser::getUsername, loginParam.getUsername()));
        // 判断用户是否存在
        if (user == null) {
            // 抛出异常
            throw new CommonExcepiton("用户不存在");
        }
        // 使用md5对密码进行加密
        String inputPassword = loginParam.getPassword();
        String encryptPassword = DigestUtil.md5Hex(inputPassword);
        System.out.println(encryptPassword);

        // 判断密码是否正确
        if (!user.getPassword().equals(encryptPassword)) {
            // 抛出异常
            throw new CommonExcepiton("密码错误");
        }

        // 创建Map存储id
        Map<String, Object> map = new HashMap<>();
        map.put("uid", user.getId());
        // 生成token
        String token = JwtUtils.createJwtToken(map);
        return token;
    }
}
